import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { Button, Upload, Icon, message, Input, InputNumber } from "antd";
import $ from 'jquery'
import ReactDOM from 'react-dom';


let rendered = false

@observer
@inject("AdminStore")
@inject("HumanBodyManageStore")
export default class upload_video_component extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList: [],//上传视频的文件列表
      recognizePeopleLimit: 1,
      frameInterval: 10,
      recognizeLastTime: 3600,
      mostRecognizeHowMuchPeople: 200,
      uploaded_video: [],//上传过的视频
      uploading: false,
      could_render: false,
    };
  }

  renderDelay = () => {
    let dom = document.getElementsByClassName('drag_div')[0].parentNode.children[1];
    if (dom) {
      this.renderText(dom);
    } else {
      setTimeout(this.renderDelay, 100)
    }
  }
  renderText = (dom) => {

    return (
      <React.Fragment>
        <h2>第一步：指定处理参数</h2>
        <div className="start_upload_button_upload_successfully" >
          <Button
            className="start_upload_button"
            style={{ backgroundColor: this.state.fileList.length === 0 ? '#f5f5f5' : "green", display: "none" }}
            type="primary"
            onClick={async () => {
              const new_fileList = await this.handleUpload();
              this.props.HumanBodyManageStore.changeNoTaskRunning(false)
              //改变父组件的refresh_get_message
              this.props.change_refresh_get_message()
              this.setState({
                fileList: new_fileList,
                uploading: false,
              }, () => {
                this.props.re_render()
              });
            }}
            disabled={this.state.fileList.length === 0}
            loading={this.state.uploading}
          >
            {this.state.uploading ? "上传中" : "开始上传"}
          </Button>
          <div className="recognize_people_limition">
            入库人像上限:
<InputNumber
              min={1}
              max={this.state.mostRecognizeHowMuchPeople}
              defaultValue={1}
              onChange={value => {
                this.recognizeHumanBodyLimitOnChangeFun(value);
              }}
            />
          </div>
          <div className="recognize_people_limition">
            视频抽样间隔(秒):
<InputNumber
              min={1}
              placeholder="单位:秒"
              defaultValue={this.state.frameInterval}
              onChange={value => {
                this.SelectFrameSkippingIntervalOnChangeFun(value);
              }}
            />
          </div>
          <div className="recognize_people_limition">
            处理最大时间(秒):
<InputNumber
              min={1}
              defaultValue={this.state.recognizeLastTime}
              onChange={value => {
                this.recognizeLastTimeOnChangeFun(value);
              }}
              placeholder="单位:秒"
            />
          </div>
        </div>
      </React.Fragment>)

  }
  render() {
    const { fileList } = this.state;
    const video_props = {
      showUploadList: { showDownloadIcon: false },
      listType: "picture",
      multiple: false,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList
          };
        });
      },
      beforeUpload: file => {
        if (file.type.toLocaleLowerCase().indexOf('video') == -1) {
          console.log('不是video')
          message.info('您上传的不是视频，仅允许上传视频')
          return false
        }
        this.setState(state => ({
          fileList: [file]
        }), async () => {
          this.props.HumanBodyManageStore.change_upload_video_ok(false)
          this.props.HumanBodyManageStore.change_created_task(true)
          message.info('视频入库任务创建中...')
          const new_fileList = await this.handleUpload();
          this.props.HumanBodyManageStore.changeNoTaskRunning(false)
          //改变父组件的refresh_get_message
          this.props.change_refresh_get_message()
          this.setState({
            fileList: new_fileList,
            uploading: false,
          }, () => {
            this.props.re_render()
          });
        });
        return false;
      },
      fileList,
    };
    return (
      <React.Fragment>
        {
          this.renderText()
        }
        <h2 style={{ marginTop: "10px" }}>第二步：上传文件</h2>
        <Upload.Dragger {...video_props} className="drag_div">
          <p className="ant-upload-drag-icon">
            <Icon type="inbox" />
          </p>
          <p className="ant-upload-text">点击或拖拽视频到此处上传</p>
          <p className="ant-upload-hint">
            只允许上传一个视频，上传文件最大为20Mb
          </p>
        </Upload.Dragger>
      </React.Fragment>
    )
  }
  componentDidMount = async () => {
    this.props.onRef(this);
  };
  reset_all_status_of_video_upload = () => {
    this.setState(prevState => ({
      fileList: [],
      recognizePeopleLimit: 1,
      frameInterval: this.state.frameInterval,
      recognizeLastTime: this.state.recognizeLastTime
    }));
  };
  recognizeHumanBodyLimitOnChangeFun = async value => {
    const databaseExistedPeopleNumber = await this.lookDatabaseExistHowMuchPeople();
    console.log(databaseExistedPeopleNumber);
    this.setState(prevState => ({
      mostRecognizeHowMuchPeople: 200 - databaseExistedPeopleNumber,
      recognizePeopleLimit: value
    }));
    console.log(this.state.mostRecognizeHowMuchPeople);
  };
  SelectFrameSkippingIntervalOnChangeFun = value => {
    console.log("changed", value);
    this.setState(prevState => ({
      frameInterval: value
    }));
  };
  recognizeLastTimeOnChangeFun = value => {
    console.log("changed", value);
    this.setState(prevState => ({
      recognizeLastTime: value
    }));
  };

  lookDatabaseExistHowMuchPeople = async () => {
    const list_database_result = await this.props.HumanBodyManageStore.ListsAllElementsOfTheFeatureLibrary(
      this.props.AdminStore.userName,
      this.props.AdminStore.token
    );
    const databaseExistedPeopleNumber = list_database_result.length
    return databaseExistedPeopleNumber;
  };
  //上传视频函数 上传视频入库函数
  handleUpload = async () => {
    this.setState({
      uploading: true
    }, () => {
      this.props.re_render()
    });
    this.setState(prevState => ({
      fileList: this.state.fileList.slice(0, 1)
    }));
    for (let [index, item] of this.state.fileList.entries()) {
      await this.props.HumanBodyManageStore.CreateHumanBodyLibraryFromImageClassMaterialFun(
        item,
        this.state.recognizePeopleLimit,
        this.state.frameInterval,
        this.state.recognizeLastTime,
        this.props.AdminStore.token
      );
      this.state.uploaded_video.push(item.name)
      this.setState((prevState) => ({
        uploaded_video: this.state.uploaded_video
      }))
    }

    return this.state.fileList;
  };
}
